# coding:utf-8
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QDropEvent
from PyQt6.QtWidgets import QListWidget
from qfluentwidgets import SmoothScrollDelegate

from common import StyleSheet


class DropListWidget(QListWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.scrollDelegate = SmoothScrollDelegate(self)
        self.setAcceptDrops(True)
        self.setDragEnabled(True)
        self.setDropIndicatorShown(True)
        self.setDragDropOverwriteMode(True)
        self.setDefaultDropAction(Qt.DropAction.MoveAction)  # Set the default drop action
        self.setDragDropMode(QListWidget.DragDropMode.InternalMove)  # 新增拖拽模式设置
        StyleSheet.LIST_VIEW.apply(self)

    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist'):
            event.acceptProposedAction()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasFormat('application/x-qabstractitemmodeldatalist'):
            event.acceptProposedAction()
        else:
            event.ignore()

    def dropEvent(self, event: QDropEvent):
        if event.source() == self:  # 仅允许内部拖拽
            # 使用标准实现代替手动移动逻辑
            super().dropEvent(event)

            # 保持选中状态
            current_row = self.currentRow()
            if current_row >= 0:
                self.setCurrentRow(current_row)
        else:
            event.ignore()
